package com.lzh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.lzh.client.OrderClients;
import com.lzh.client.TicketClients;
import com.lzh.pojo.repVo.*;
import com.lzh.service.PayService;
import com.lzh.utils.AlipayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author Li
 * @ 2022/3/28
 */
@Service
public class PayServiceImpl implements PayService {

    @Autowired
    AlipayUtils alipayUtils;
    @Autowired
    RabbitTemplate rabbitTemplate;
    private static Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);

    @Autowired
    OrderClients orderClients ;

    @Autowired
    TicketClients ticketClients ;
    //付款
    @Override
    public BaseResp pay(Map map) {
        logger.debug("进入支付页面：" + map) ;
        String orderId = map.get("orderId").toString();
        BaseResp byOrderId = orderClients.findByOrderid(orderId);
        if (byOrderId.getCode() == 0){
            return byOrderId ;
        }
        Object data = byOrderId.getData();
        String s = JSONObject.toJSONString(data);
        TgOrder tgOrder = JSONObject.parseObject(s, TgOrder.class);

        String pay = alipayUtils.pay(orderId, tgOrder.getOrderPrice());
        logger.debug("获取到的支付宝的提交form为："+pay);

        BaseResp baseResp = orderClients.updateStatus(orderId, 3);

        if (baseResp.getCode() == 0){
            return new BaseResp(0 , "支付失败" , null , null) ;
        }
        rabbitTemplate.convertAndSend("pay-dead-exchange", "deadpay", orderId, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration("60000");
                return message;
            }
        });
        return new BaseResp(1,"支付调用成功！",pay,null);
    }

    @Override
    public void notifyResult(HttpServletRequest request) {
        logger.debug("进入支付宝回调接口");
        Map map = alipayUtils.notifyResult(request);
        logger.debug("支付宝回调的参数为"+map) ;
        if ((Boolean) map.get("signVerified")){
            logger.debug("支付宝验签成功!");
            Map payResult =(Map) map.get("payResult");
            Double total_amount = Double.valueOf(payResult.get("total_amount").toString());
            String out_trade_no = payResult.get("out_trade_no").toString();
            String trade_status = payResult.get("trade_status").toString();
            if (trade_status.equals("TRADE_SUCCESS")){
                logger.debug("支付宝返回状态为 支付成功！继续流程{}") ;
                BaseResp byOrderid = orderClients.findByOrderid(out_trade_no);
                Object data = byOrderid.getData();
                String s = JSONObject.toJSONString(data);
                TgOrder tgOrder = JSONObject.parseObject(s, TgOrder.class);
                //继续进行支付的 价格比对
                if (total_amount.compareTo(tgOrder.getOrderPrice())==0){
                    //说明用户支付的金额与数据库保持一致，支付结束，将order表中的支付状态更改为已支付

                    //将 票数－1
                    BaseResp byOrderid1 = orderClients.findByOrderid(out_trade_no);
                    orderClients.findDetailByOrderid(out_trade_no) ;
                    Object data2 = byOrderid1.getData();
                    String s2 = JSONObject.toJSONString(data2);
                    TgOrder tgOrder1 = JSONObject.parseObject(s2, TgOrder.class);
                    Integer ticketId = tgOrder1.getTicketId();

                    BaseResp detailByOrderid = orderClients.findDetailByOrderid(out_trade_no);
                    Object data1 = detailByOrderid.getData();
                    String s1 = JSONObject.toJSONString(data1);
                    List list = JSONObject.parseObject(s1, List.class);
                    for (Object o : list) {
                        String delail = JSONObject.toJSONString(o);
                        TgOrderDetail tgOrderDetail = JSONObject.parseObject(delail, TgOrderDetail.class);
                        String seatType = tgOrderDetail.getSeatType();

                        UpdateRes updateRes = new UpdateRes() ;
                        updateRes.setTicketId(ticketId) ;
                        updateRes.setTrainSeatType(Integer.valueOf(seatType));
                        updateRes.setUpdateType(-1);
                        logger.debug("修改座位参数："+updateRes);
                        ticketClients.update(updateRes) ;
                    }
                    BaseResp baseResp = orderClients.updateStatus(out_trade_no,2);

                    if (baseResp.getCode()==1){
                        logger.debug("订单状态修改为 已支付！");
                    }
                }
            }
        }
    }

    //退票
    @Override
    public BaseResp refundTicket(Map map) {

        String  orderDetailId = map.get("orderDetailId").toString() ;
        //获取OrderDetail
        BaseResp detailByOrderid = orderClients.findByDetailByOrderDetail(orderDetailId) ;
        Object data = detailByOrderid.getData();
        //获取orderId
        String s = JSONObject.toJSONString(data);
        TgOrderDetail tgOrderDetail = JSONObject.parseObject(s, TgOrderDetail.class);
        String orderId = tgOrderDetail.getOrderId();
        Double price = tgOrderDetail.getPrice();
        //获取order
        BaseResp byOrderid = orderClients.findByOrderid(orderId);
        Object data1 = byOrderid.getData();
        String s1 = JSONObject.toJSONString(data1);
        TgOrder tgOrder = JSONObject.parseObject(s1, TgOrder.class);

        if (!StringUtils.isEmpty(orderDetailId) && price != null && price != 0){
            String refund = alipayUtils.refund(orderDetailId, price);
            System.out.println("SDK"+refund);
            // refund   :1 退款成功   refund: 0 退款失败
            if (!StringUtils.isEmpty(refund)){
                //修改订单状态
                orderClients.updateStatus(orderId , 5) ;

                UpdateRes updateRes = new UpdateRes() ;
                updateRes.setTicketId(tgOrder.getTicketId());
                updateRes.setUpdateType(Integer.valueOf(tgOrderDetail.getSeatType()));
                updateRes.setTrainSeatType(1);
                //对应票数 +1
                BaseResp update = ticketClients.update(updateRes);
                return new BaseResp(1 , "退款成功" , refund , null) ;
            }
        }
        return new BaseResp(0 , "退款失败" , null , null) ;
    }


    @Override
    public BaseResp travelPay(Map map) {

        return new BaseResp(1,"支付成功！",null,null);
    }
}
